//
//  PywRegisterLoginPwdViewController.m
//  PywSdk2.2_Test
//
//  Created by smallwave on 16/8/1.
//  Copyright © 2016年 yyft. All rights reserved.
//

#import "PywRegisterLoginPwdViewController.h"
#import "PywMasonry.h"
#import "PywTextFieldView.h"
#import "UIButton+Pyw.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywPassportRegisterApi.h"
#import "PywSdk+login.h"
#import "PywCPNotifications.h"
#import "ApiClientConst.h"
#import "PywRSAUtil.h"
#import "PywBuriedManager.h"

#define kPasswordMinLenght 6
#define kPasswordMaxLenght 12

@interface PywRegisterLoginPwdViewController ()

@property (nonatomic, strong) PywTextFieldView          *loginPwdView;          // 登陆密码输入框
@property (nonatomic, strong) UIButton                  *registerAndLoginBtn;   // 注册并登陆按钮

@property (nonatomic, copy) NSString                    *phoneNumber;           // 手机号码
@property (nonatomic, copy) NSString                    *is_check_smscode;      // 校验密码已经通过的标记位
@property (nonatomic, copy) NSString                    *smsType;               // 获取验证码场景类型
@property (nonatomic, copy) NSString                    *account;               // 注册时新建的游戏账号

@property (nonatomic, strong) PywPassportRegisterApi    *registerApi;           // 快速注册

@end

@implementation PywRegisterLoginPwdViewController
{
    BOOL _wasKeyBoardManagerEnabled;
}

#pragma mark - Init
- (instancetype)initWithPhoneNumber:(NSString *)phoneNumber
                     IsCheckSmsCode:(NSString *)is_check_smscode
                            SmsType:(NSString *)smsType{
    self = [super init];
    if (self) {
        self.phoneNumber = phoneNumber;
        self.is_check_smscode = is_check_smscode;
        self.smsType = smsType;
    }
    return self;
}

#pragma mark - Lift Cycle Method
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUp];
}

#pragma mark - prepareUI
- (void)setUp{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"手机注册(3/3)";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self addSubviewsAndLayoutSubviews];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSLog(@"%s",__FUNCTION__);
    [PywBuriedManager manager].page_sn = @"9";
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"9" actionSn:@"1" typeSn:@"1"];
    _wasKeyBoardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:85];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSLog(@"%s",__FUNCTION__);
    [[IQKeyboardManager sharedManager] setEnable:_wasKeyBoardManagerEnabled];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    NSLog(@"%s",__FUNCTION__);
    [PywBuriedManager manager].page_sn = @"";
//    [[PywBuriedManager sharedBuriedManager] saveUserActionDataWithPageSn:@"9" actionSn:@"2" typeSn:@"2"];
}
- (void)returnback
{
    [super returnback];
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"9" actionSn:@"7" typeSn:@"3"];
}

- (void)addSubviewsAndLayoutSubviews{
    [self.view addSubview:self.loginPwdView];
    [self.view addSubview:self.registerAndLoginBtn];
    
    __weak typeof(self) wSelf = self;
    [self.loginPwdView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.view.mas_top).offset(80);
        make.width.equalTo(wSelf.view.mas_width).multipliedBy(0.85);
        make.height.equalTo(@40);
    }];
    
    [self.registerAndLoginBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(wSelf.loginPwdView.mas_bottom).offset(40);
        make.width.height.equalTo(wSelf.loginPwdView);
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - Action
- (void)registerAndLoginBtnAction{
    [self.view endEditing:YES];
    [self.loginPwdView resignFirstResponder];
    
    if (self.loginPwdView.text.length < kPasswordMinLenght) {
        
        [PywMBProgressHUD showError:@"密码不能低于6位" toView:self.navigationController.view];
    } else if (self.loginPwdView.text.length > kPasswordMaxLenght){
        
        [PywMBProgressHUD showError:@"密码不能超出12位" toView:self.navigationController.view];
    } else {
        
        [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"9" actionSn:@"14" typeSn:@"3"];
        /// 快速注册成功
        [self.registerApi requestRegisterWithParams:[self requestRegisterParams] success:^(NSString *status, id anyObjct) {
            
            self.account = [NSString stringWithFormat:@"%@",anyObjct];
            
            MutableDictionary *param = [[MutableDictionary alloc] init];
            NSString *password = [PywRSAUtil encryptString:self.loginPwdView.text];
            [param setObject:self.phoneNumber forKey:@"passport"];
            [param setObject:password forKey:@"password"];
            
            // 注册成功，关闭当前控制器并发送通知
            [self dismissViewControllerAnimated:YES
                                     completion:^{
                                         [[NSNotificationCenter defaultCenter] postNotificationName:DidRegisterSuccess
                                                                                             object:param];
                                     }];
            
        } fail:^(NSError *error) {
            
        }];
    }
}
/**
 *  快速注册  传入的参数
 *
 *  @return <#return value description#>
 */
- (MutableDictionary *)requestRegisterParams{
    NSString *passport = [self.phoneNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *password = [self.loginPwdView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *smstype = [self.smsType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *is_check_smscode = [self.is_check_smscode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    MutableDictionary *params = [[MutableDictionary alloc] init];
    [params setObject:passport forKey:@"passport"];
    [params setObject:password forKey:@"password"];
    [params setObject:smstype forKey:@"smstype"];
    [params setObject:is_check_smscode forKey:@"is_check_smscode"];
    return params;
}


#pragma mark - Lazy
- (PywTextFieldView *)loginPwdView{
    if (!_loginPwdView) {
        _loginPwdView = [PywTextFieldView passwordTextFieldWithLeftImg:@"icon_password_normal"
                                                       TextPlaceholder:@"请输入登录密码（限6-12字符）"
                                                       ButtonNormalImg:@"icon_visible_normal"
                                                     ButtonSelectedImg:@"icon_visible_disabled"];
        [_loginPwdView setAccessibilityId:@"phonereg_pswd"];
    }
    return _loginPwdView;
}
- (UIButton *)registerAndLoginBtn{
    if (!_registerAndLoginBtn) {
        _registerAndLoginBtn = [UIButton buttonWithBackgroundColor:RGB(238, 151, 15, 1)
                                                      cornerRadius:20
                                                        titleColor:[UIColor whiteColor]
                                                titleLabelFontSize:18
                                                             title:@"注册并登录"];
        [_registerAndLoginBtn addTarget:self action:@selector(registerAndLoginBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_registerAndLoginBtn setAccessibilityIdentifier:@"phonereg_btn"];
    }
    return _registerAndLoginBtn;
}
- (PywPassportRegisterApi *)registerApi{
    if (!_registerApi) {
        _registerApi = [PywPassportRegisterApi manager];
    }
    return _registerApi;
}


@end
